<template>
  <view class="container">
    <!-- 服务图片 -->
    <image :src="service.internalServiceImage" class="service-image" mode="widthFix" />

    <!-- 按钮区域 -->
    <view class="button-group">
      <button 
        v-for="(button, index) in buttons" 
        :key="index" 
        :class="['tab-button', { active: activeTab === button.key }]"
        @click="handleTabClick(button.key)"
      >
        {{ button.label }}
      </button>
    </view>

    <!-- 内容区域 -->
    <view class="content">
      <!-- 产品说明 -->
      <view v-if="activeTab === 'productDescription'" class="rich-text">
        <rich-text :nodes="service.productDescription"></rich-text>
      </view>

      <!-- 产品介绍 -->
      <view v-if="activeTab === 'productIntroduction'" class="rich-text">
        <rich-text :nodes="service.productIntroduction"></rich-text>
      </view>

      <!-- 客服热线 -->
      <view v-if="activeTab === 'customerServiceHotline'" class="rich-text">
        <rich-text :nodes="service.customerServiceHotline"></rich-text>
      </view>
    </view>

    <!-- 确认按钮 -->
    <view class="confirm-button">
      <view class="price-display">
        {{ service.priceDescription || '请选择服务' }}
      </view>
      <view class="button-group">
        <button class="call-button" @click="handleCall">拨打电话</button>
        <view class="divider"></view>
        <button 
          class="order-button"
          @click="handleOrder"
        >
          立即下单
        </button>
        <view class="divider"></view>
        <button 
          class="contact-button" 
          @click="handleConfirm"
        >
          联系客服
        </button>
      </view>
    </view>

    <!-- 授权按钮 -->
    <view v-if="showAuthButton" class="auth-button-container">
      <button 
        open-type="getPhoneNumber" 
        @getphonenumber="handleGetPhoneNumber"
        class="auth-button"
      >
        授权获取手机号
      </button>
    </view>

    <!-- 自定义提示窗口 -->
    <view v-if="showAuthModal" class="auth-modal">
      <view class="auth-modal-content">
        <view class="auth-modal-header">
          <text class="auth-modal-title">提示</text>
        </view>
        <view class="auth-modal-body">
          <text class="auth-modal-text">您还未登录，请先授权获取手机号</text>
        </view>
        <view class="auth-modal-footer">
          <button 
            class="auth-modal-button auth-modal-button-cancel"
            @click="showAuthModal = false"
          >
            取消
          </button>
          <button 
            class="auth-modal-button auth-modal-button-confirm"
            open-type="getPhoneNumber"
            @getphonenumber="handleGetPhoneNumber"
          >
            授权登录
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { wxLogin ,clickservice} from '@/api/wxlogin/wxlogin';

const service = ref({});
const activeTab = ref('productDescription');
const buttons = ref([
  { key: 'productDescription', label: '服务内容' },
  { key: 'productIntroduction', label: '服务说明' },
  { key: 'customerServiceHotline', label: '客服热线' }
]);

// 处理富文本中的图片自适应
const processRichText = (html) => {
  if (!html) return '';
  return html.replace(/<img[^>]*>/gi, (match) => {
    return match.replace(/(<img[^>]*)(style="[^"]*")?([^>]*>)/gi, '$1 style="max-width:100%;height:auto;" $3');
  });
};

// 微信登录
const wxLoginHandler = () => {
  return new Promise((resolve, reject) => {
    uni.login({
      provider: 'weixin',
      success: async (loginRes) => {
        try {
          const res = await wxLogin({ code: loginRes.code });
          if (res.code === 200) {
            uni.setStorageSync('isLoggedIn', true);
            uni.setStorageSync('userId', res.data.userId);
            resolve(true);
          } else {
            reject(new Error(res.msg || '登录失败'));
          }
        } catch (err) {
          reject(err);
        }
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
};


// 处理返回按钮
const handleBack = () => {
  uni.navigateBack();
};

// 处理获取手机号
const handleGetPhoneNumber = async (e) => {
  if (e.detail.errMsg !== 'getPhoneNumber:ok') {
    uni.showToast({
      title: '获取手机号失败',
      icon: 'none'
    });
    return;
  }

  try {
    // 获取手机号
    const res = await wxLogin({ code: e.detail.code });
    if (res.code === 200) {
      // 保存用户信息
      uni.setStorageSync('isLoggedIn', true);
      uni.setStorageSync('userId', res.data.userId);
      console.log(res.data.userId);
      uni.setStorageSync('phoneNumber', res.data.phoneNumber);
      uni.setStorageSync('userInfo', JSON.stringify({
        name: res.data.name,
        gender: res.data.gender,
        age: res.data.age,
        birthday: res.data.birthday
      }));
      uni.showToast({
        title: '登录成功',
        icon: 'success'
      });
      // 登录成功后关闭提示窗口
      showAuthModal.value = false;
    } else {
      throw new Error(res.msg || '获取手机号失败');
    }
  } catch (err) {
    console.error('获取手机号失败:', err);
    uni.showToast({
      title: err.message || '获取手机号失败',
      icon: 'none'
    });
  }
};

// 添加发送点击记录的方法
const sendClickRecord = async () => {
  const userId = uni.getStorageSync('userId');
  console.log('userId:', userId);
  console.log('service.value:', service.value);
  
  if (userId && service.value.serviceName) {
    try {
      console.log('Calling clickservice with:', userId, service.value.serviceName);
      await clickservice(userId, service.value.serviceName);
      console.log('点击记录发送成功');
    } catch (err) {
      console.error('发送点击记录失败:', err);
      console.error('错误详情:', err.response || err.message || err);
    }
  } else {
    console.error('无法发送点击记录：缺少必要的参数');
    console.error('userId:', userId);
    console.error('service.value:', service.value);
    console.error('service.value.serviceName:', service.value?.serviceName);
  }
};

// 在script setup中添加showAuthModal
const showAuthModal = ref(false);

// 修改联系客服方法
const handleConfirm = async () => {
  // 检查是否登录
  if (!uni.getStorageSync('isLoggedIn')) {
    showAuthModal.value = true;
    return;
  }

  // 发送点击记录
  await sendClickRecord();
  
  // 已登录，跳转到客服页面
  uni.navigateTo({
    url: `/pages/customer-platform/my/customerService`
  });
};

// 修改拨打电话方法
const handleCall = () => {
  // 检查是否登录
  if (!uni.getStorageSync('isLoggedIn')) {
    showAuthModal.value = true;
    return;
  }

  // 发送点击记录
  sendClickRecord();
  uni.makePhoneCall({
    phoneNumber: '18060924226' // 替换为实际的客服电话
  });
};

// 处理标签点击
const handleTabClick = (tab) => {
  activeTab.value = tab;
};

// 在 onLoad 中处理富文本内容
onLoad((options) => {
  if (options.service) {
    const parsedService = JSON.parse(decodeURIComponent(options.service));
    parsedService.productDescription = processRichText(parsedService.productDescription);
    parsedService.productIntroduction = processRichText(parsedService.productIntroduction);
    parsedService.customerServiceHotline = processRichText(parsedService.customerServiceHotline);
    service.value = parsedService;
  }
});

// 在 script 部分添加跳转逻辑
const handleOrder = () => {
  uni.navigateTo({
    url: `/pages/customer-platform/index/menu/homeClean/orderDetail?service=${encodeURIComponent(JSON.stringify(service.value))}`
  });
};
</script>

<style scoped lang="scss">
.container {
  padding: 32rpx;
  background-color: #fff;
  min-height: 100vh;
}

.service-image {
  width: 100%;
  height: 25vh;
  border-radius: 16rpx;
  margin-bottom: 16rpx;
}

.button-group {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16rpx;
  gap: 4rpx;

  .tab-button {
    flex: 1;
    padding: 0 8rpx;
    background-color: #f5f5f5;
    color: #333;
    border-radius: 8rpx;
    font-size: 24rpx;
    height: 60rpx;
    line-height: 60rpx;
    margin: 0;

    &.active {
      background-color: #ffcc00;
      color: #fff;
    }
  }
}

.content {
  padding: 20rpx;
  position: relative;
}

.rich-text {
  padding: 24rpx;
  background-color: #f5f5f5;
  border-radius: 16rpx;
  margin-bottom: 200rpx;
}

.confirm-button {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 24rpx;
  box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.1);
  z-index: 10;
  
  .price-display {
    font-size: 32rpx;
    color: #ff0000;
    font-weight: bold;
    &::before {
      content: '¥';
      font-size: 24rpx;
      margin-right: 4rpx;
    }
  }

  .button-group {
    display: flex;
    align-items: center;
    border-radius: 50rpx;
    overflow: hidden;
    border: 1rpx solid #ffcc00;

    .call-button,
    .contact-button {
      flex: 1;
      background-color: #ffcc00;
      color: #333;
      height: 80rpx;
      line-height: 80rpx;
      font-size: 32rpx;
      margin: 0;
      border-radius: 0;
    }

    .divider {
      width: 1rpx;
      height: 60rpx;
      background-color: #fff;
    }
  }
}

.auth-button-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx;
  background-color: #fff;
  z-index: 999;
}

.auth-button {
  width: 100%;
  background-color: #ffcc00;
  color: #333;
  border-radius: 8rpx;
  font-size: 32rpx;
  height: 80rpx;
  line-height: 80rpx;
}

.auth-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.auth-modal-content {
  width: 80%;
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
}

.auth-modal-header {
  padding: 32rpx;
  border-bottom: 1rpx solid #eee;
}

.auth-modal-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.auth-modal-body {
  padding: 32rpx;
}

.auth-modal-text {
  font-size: 28rpx;
  color: #666;
}

.auth-modal-footer {
  display: flex;
  border-top: 1rpx solid #eee;
}

.auth-modal-button {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  font-size: 28rpx;
  border-radius: 0;
  margin: 0;
}

.auth-modal-button-cancel {
  background-color: #f5f5f5;
  color: #333;
}

.auth-modal-button-confirm {
  background-color: #ffcc00;
  color: #333;
}

.order-button {
  flex: 1;
  background-color: #ffcc00;
  color: #fff;
  border-radius: 8rpx;
  font-size: 28rpx;
  height: 80rpx;
  line-height: 80rpx;
  margin: 0 8rpx;
}

.divider {
  width: 1rpx;
  background-color: #eee;
  margin: 0 8rpx;
}
</style> 